﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using nGSO.Model;
using System.Text.RegularExpressions;
using System.Data.SqlServerCe;
using System.Data.SqlClient;

namespace nGSO.Performance
{
    public static class PerfDatabase
    {
        public static string SelectedDatabaseFileName { get; set; }

        static PerfDatabase()
        {
            SelectedDatabaseFileName = Regex.Match(ConfigurationManager.ConnectionStrings["DataModelEntities"].ConnectionString, @"Data Source=(\w+\.sdf)").Groups[1].Value;
        }

        public static FileInfo[] GetDatabases()
        {
            DirectoryInfo currentDir = new DirectoryInfo(System.Environment.CurrentDirectory);
            var dbs = currentDir.GetFiles("*.sdf");

            if (dbs.Count() == 0)
            {
                CreatePerfDatabase();

                dbs = currentDir.GetFiles("*.sdf");
            }

            return dbs;
        }

        public static void CreatePerfDatabase()
        {
            string tempConnectionStr = string.Format("Data Source=\"{0}\";", "DataModel.sdf");
            SqlCeEngine en = new SqlCeEngine(tempConnectionStr);
            en.CreateDatabase();

            using (SqlCeConnection connection = new SqlCeConnection(tempConnectionStr))
            {
                connection.Open();

                StringBuilder createSchemaScript = new StringBuilder(File.ReadAllText("schema.sqlce"));
                createSchemaScript.Replace("\r\n", string.Empty);

                SqlCeCommand command = new SqlCeCommand(string.Format("EXEC SP_EXECUTESQL('{0}')", createSchemaScript.ToString()), connection);
                command.ExecuteNonQuery();

            }
        }

        public static DataModelEntities GetContext()
        {
            ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["DataModelEntities"];
            string cs = connectionString.ConnectionString;

            cs = Regex.Replace(cs, @"Data Source=\w+\.sdf", "Data source=" + SelectedDatabaseFileName);

            return new DataModelEntities(cs);
        }

        public static void ClearAllResults()
        {
            using (Model.DataModelEntities ctx = PerfDatabase.GetContext())
            {
                ctx.ExecuteStoreCommand("delete from PerfEntryHistory");
                ctx.ExecuteStoreCommand("delete from PerfKp");
                ctx.ExecuteStoreCommand("delete from PerfTests");
                ctx.ExecuteStoreCommand("delete from PerfKpResult");
            }
            
        }
    }
}
